﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LMKJ.Classes;
using System.Collections;
using System.Text.RegularExpressions;

namespace LMKJ
{
    public partial class editshoppinglist : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                dateInit();
                existingItemsInit();

                int lid = Convert.ToInt32(Request.QueryString["details"]);

                ShoppingList sl = DatabaseManager.RetrieveShoppingListById(lid);

                if (sl != null)
                {
                    lidLbl.Text = sl.List_id.ToString();
                    nricLbl.Text = sl.Nric;
                    nearestVolunteersInit();
                    dateLbl.Text = sl.Date;
                    string[] dateReq = sl.Date_req.Split('-');
                    int dayReq = Convert.ToInt32(dateReq[0]);
                    int monthReq = Convert.ToInt32(dateReq[1]);
                    int yearReq = Convert.ToInt32(dateReq[2]);
                    monthReqDdl.SelectedIndex = monthReq;
                    dayReqInit();
                    dayReqDdl.SelectedIndex = dayReq;
                    yearReqDdl.SelectedIndex = yearReq - DateTime.Today.Year + 1;
                    if (sl.Date_pur != null)
                    {
                        string[] datePur = sl.Date_pur.Split('-');
                        int dayPur = Convert.ToInt32(datePur[0]);
                        int monthPur = Convert.ToInt32(datePur[1]);
                        int yearPur = Convert.ToInt32(datePur[2]);
                        monthPurDdl.SelectedIndex = monthPur;
                        dayPurInit();
                        dayPurDdl.SelectedIndex = dayPur;
                        yearPurDdl.SelectedIndex = yearPur - DateTime.Today.Year + 1;
                    }
                    if (sl.Date_del != null)
                    {
                        string[] dateDel = sl.Date_del.Split('-');
                        int dayDel = Convert.ToInt32(dateDel[0]);
                        int monthDel = Convert.ToInt32(dateDel[1]);
                        int yearDel = Convert.ToInt32(dateDel[2]);
                        monthDelDdl.SelectedIndex = monthDel;
                        dayDelInit();
                        dayDelDdl.SelectedIndex = dayDel;
                        yearDelDdl.SelectedIndex = yearDel - DateTime.Today.Year + 1;
                    }
                    int status;
                    if (sl.Status.Equals("Pending"))
                    {
                        status = 0;
                    }
                    else
                    {
                        status = 1;
                    }
                    statusRbl.SelectedIndex = status;
                    ArrayList itemsList = DatabaseManager.RetrieveItemListByListId(lid);

                    foreach (ItemList i in itemsList)
                    {
                        itemsListLbox.Items.Add(i.Item_name + " - " + i.Qty);
                    }
                }
            }
        }

        protected void dateInit()
        {
            int thisYear = DateTime.Today.Year;

            for (int m = 1; m <= 12; m++)
            {
                monthReqDdl.Items.Add(m.ToString());
                monthPurDdl.Items.Add(m.ToString());
                monthDelDdl.Items.Add(m.ToString());
            }

            for (int y = thisYear; y <= thisYear + 1; y++)
            {
                yearReqDdl.Items.Add(y.ToString());
                yearPurDdl.Items.Add(y.ToString());
                yearDelDdl.Items.Add(y.ToString());
            }
        }

        protected void dayReqInit()
        {
            int monthNo;
            int dayNo = 0;

            dayReqDdl.Enabled = true;
            yearReqDdl.Enabled = true;

            if (dayReqDdl.SelectedIndex > 1)
            {
                dayNo = Convert.ToInt32(dayReqDdl.SelectedItem.Text);
            }

            dayReqDdl.Items.Clear();
            dayReqDdl.Items.Add("Day");

            monthNo = monthReqDdl.SelectedIndex;

            for (int d = 1; d <= 31; d++)
            {
                dayReqDdl.Items.Add(d.ToString());
                if (monthNo == 2 && d == 29)
                {
                    break;
                }
                else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                {
                    break;
                }
            }

            if (dayReqDdl.Items.Count - 1 >= dayNo)
            {
                dayReqDdl.SelectedIndex = dayNo;
            }
        }

        protected void dayPurInit()
        {
            int monthNo;
            int dayNo = 0;

            dayPurDdl.Enabled = true;
            yearPurDdl.Enabled = true;

            if (dayPurDdl.SelectedIndex > 1)
            {
                dayNo = Convert.ToInt32(dayPurDdl.SelectedItem.Text);
            }

            dayPurDdl.Items.Clear();
            dayPurDdl.Items.Add("Day");

            monthNo = monthPurDdl.SelectedIndex;

            for (int d = 1; d <= 31; d++)
            {
                dayPurDdl.Items.Add(d.ToString());
                if (monthNo == 2 && d == 29)
                {
                    break;
                }
                else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                {
                    break;
                }
            }

            if (dayPurDdl.Items.Count - 1 >= dayNo)
            {
                dayPurDdl.SelectedIndex = dayNo;
            }
        }

        protected void dayDelInit()
        {
            int monthNo;
            int dayNo = 0;

            dayDelDdl.Enabled = true;
            yearDelDdl.Enabled = true;

            if (dayDelDdl.SelectedIndex > 1)
            {
                dayNo = Convert.ToInt32(dayDelDdl.SelectedItem.Text);
            }

            dayDelDdl.Items.Clear();
            dayDelDdl.Items.Add("Day");

            monthNo = monthDelDdl.SelectedIndex;

            for (int d = 1; d <= 31; d++)
            {
                dayDelDdl.Items.Add(d.ToString());
                if (monthNo == 2 && d == 29)
                {
                    break;
                }
                else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                {
                    break;
                }
            }

            if (dayDelDdl.Items.Count - 1 >= dayNo)
            {
                dayDelDdl.SelectedIndex = dayNo;
            }
        }

        protected void nearestVolunteersInit()
        {
            Resident r = DatabaseManager.RetrieveResidentByNric(nricLbl.Text);
            string postalSect = r.Postal.Remove(2);

            ArrayList nearestVolunteers = DatabaseManager.RetrieveVolunteerIdsByPostal(postalSect);
            foreach (int id in nearestVolunteers)
            {
                volunteerIdDdl.Items.Add(id.ToString());
            }
        }

        protected void existingItemsInit()
        {
            ArrayList existingItems = DatabaseManager.RetrieveAllItemName();
            foreach (string item in existingItems)
            {
                existingItemsDdl.Items.Add(item);
            }
        }

        protected void monthReqDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            int monthNo;
            int dayNo = 0;

            if (monthReqDdl.SelectedItem.Text != "Month")
            {
                dayReqDdl.Enabled = true;
                yearReqDdl.Enabled = true;

                if (dayReqDdl.SelectedIndex > 1)
                {
                    dayNo = Convert.ToInt32(dayReqDdl.SelectedItem.Text);
                }

                dayReqDdl.Items.Clear();
                dayReqDdl.Items.Add("Day");

                monthNo = monthReqDdl.SelectedIndex;

                for (int d = 1; d <= 31; d++)
                {
                    dayReqDdl.Items.Add(d.ToString());
                    if (monthNo == 2 && d == 29)
                    {
                        break;
                    }
                    else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                    {
                        break;
                    }
                }

                if (dayReqDdl.Items.Count - 1 >= dayNo)
                {
                    dayReqDdl.SelectedIndex = dayNo;
                }
            }
            else if (monthReqDdl.SelectedItem.Text == "Month")
            {
                dayReqDdl.SelectedIndex = 0;
                yearReqDdl.SelectedIndex = 0;
                dayReqDdl.Enabled = false;
                yearReqDdl.Enabled = false;
            }
        }

        protected void monthPurDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            int monthNo;
            int dayNo = 0;

            if (monthPurDdl.SelectedItem.Text != "Month")
            {
                dayPurDdl.Enabled = true;
                yearPurDdl.Enabled = true;

                if (dayPurDdl.SelectedIndex > 1)
                {
                    dayNo = Convert.ToInt32(dayPurDdl.SelectedItem.Text);
                }

                dayPurDdl.Items.Clear();
                dayPurDdl.Items.Add("Day");

                monthNo = monthPurDdl.SelectedIndex;

                for (int d = 1; d <= 31; d++)
                {
                    dayPurDdl.Items.Add(d.ToString());
                    if (monthNo == 2 && d == 29)
                    {
                        break;
                    }
                    else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                    {
                        break;
                    }
                }

                if (dayPurDdl.Items.Count - 1 >= dayNo)
                {
                    dayPurDdl.SelectedIndex = dayNo;
                }
            }
            else if (monthPurDdl.SelectedItem.Text == "Month")
            {
                dayPurDdl.SelectedIndex = 0;
                yearPurDdl.SelectedIndex = 0;
                dayPurDdl.Enabled = false;
                yearPurDdl.Enabled = false;
            }
        }

        protected void monthDelDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            int monthNo;
            int dayNo = 0;

            if (monthDelDdl.SelectedItem.Text != "Month")
            {
                dayDelDdl.Enabled = true;
                yearDelDdl.Enabled = true;

                if (dayDelDdl.SelectedIndex > 1)
                {
                    dayNo = Convert.ToInt32(dayDelDdl.SelectedItem.Text);
                }

                dayDelDdl.Items.Clear();
                dayDelDdl.Items.Add("Day");

                monthNo = monthDelDdl.SelectedIndex;

                for (int d = 1; d <= 31; d++)
                {
                    dayDelDdl.Items.Add(d.ToString());
                    if (monthNo == 2 && d == 29)
                    {
                        break;
                    }
                    else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                    {
                        break;
                    }
                }

                if (dayDelDdl.Items.Count - 1 >= dayNo)
                {
                    dayDelDdl.SelectedIndex = dayNo;
                }
            }
            else if (monthDelDdl.SelectedItem.Text == "Month")
            {
                dayDelDdl.SelectedIndex = 0;
                yearDelDdl.SelectedIndex = 0;
                dayDelDdl.Enabled = false;
                yearDelDdl.Enabled = false;
            }
        }

        protected void confirmBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                ShoppingList updatedSl = new ShoppingList();
                updatedSl.List_id = Convert.ToInt32(Request.QueryString["details"]);
                updatedSl.Volunteer_id = Convert.ToInt32(volunteerIdDdl.SelectedItem.Text);
                updatedSl.Date_req = yearReqDdl.SelectedItem.Text + "-" + monthReqDdl.SelectedItem.Text + "-" + dayReqDdl.SelectedItem.Text;
                if (!(monthPurDdl.SelectedIndex == 0 || dayPurDdl.SelectedIndex == 0 || yearPurDdl.SelectedIndex == 0))
                {
                    updatedSl.Date_pur = yearPurDdl.SelectedItem.Text + "-" + monthPurDdl.SelectedItem.Text + "-" + dayPurDdl.SelectedItem.Text;
                }
                if (!(monthDelDdl.SelectedIndex == 0 || dayDelDdl.SelectedIndex == 0 || yearDelDdl.SelectedIndex == 0))
                {
                    updatedSl.Date_del = yearDelDdl.SelectedItem.Text + "-" + monthDelDdl.SelectedItem.Text + "-" + dayDelDdl.SelectedItem.Text;
                }
                updatedSl.Status = statusRbl.SelectedItem.Text;

                int success = DatabaseManager.UpdateShoppingList(updatedSl);

                if (success == 1)
                {
                    DatabaseManager.DeleteAllItemList(updatedSl.List_id);

                    foreach (ListItem i in itemsListLbox.Items)
                    {
                        ItemList il = new ItemList();
                        il.List_id = updatedSl.List_id;
                        string[] item = i.Text.Split('-');
                        il.Item_name = item[0].Trim();
                        il.Qty = Convert.ToInt32(item[1].Trim());

                        success = DatabaseManager.CreateItemList(il);
                    }

                    if (success == 1)
                    {
                        string jsPopup = "<script type='text/javascript'>" +
                            "alert('Successfully Updated Shopping List!');" +
                            "window.location.href = 'viewshoppinglistdetails.aspx?details=" +
                            Request.QueryString["details"] +
                            "';" +
                            "</script>";
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", jsPopup);
                    }
                }
            }
        }

        protected void cancelBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("viewshoppinglistdetails.aspx?details=" + Request.QueryString["details"]);
        }

        protected void deleteBtn_Click(object sender, EventArgs e)
        {
            confirmationLbl.Visible = true;
            confirmationBtn.Visible = true;
        }

        protected void addItemToLboxBtn_Click(object sender, EventArgs e)
        {
            bool itemFound = false;

            foreach (ListItem i in itemsListLbox.Items)
            {
                if (i.Text.Split('-')[0].Trim().Equals(existingItemsDdl.SelectedItem.Text))
                {
                    itemFound = true;
                    break;
                }
            }

            if (!itemFound && Convert.ToInt32(quantityTbx.Text) > 0)
            {
                itemsListLbox.Items.Add(existingItemsDdl.SelectedItem.Text + " - " + quantityTbx.Text);
            }
        }

        protected void removeItemFromLboxBtn_Click(object sender, EventArgs e)
        {
            if (itemsListLbox.Items.Count > 0)
            {
                int[] removeItems = itemsListLbox.GetSelectedIndices();
                for (int i = removeItems.Length - 1; i >= 0; i--)
                {
                    itemsListLbox.Items.RemoveAt(removeItems[i]);
                }
            }
        }

        protected void fieldsValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (monthReqDdl.SelectedIndex == 0 || dayReqDdl.SelectedIndex == 0 || yearReqDdl.SelectedIndex == 0)
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        protected void dateReqValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (monthReqDdl.SelectedIndex != 0 && dayReqDdl.SelectedIndex != 0 && yearReqDdl.SelectedIndex != 0)
            {
                string selectedReqDate = string.Format("{0:0000}", yearReqDdl.SelectedItem.Text) +
                    string.Format("{0:00}", monthReqDdl.SelectedItem.Text) +
                    string.Format("{0:00}", dayReqDdl.SelectedItem.Text);
                ShoppingList sl = DatabaseManager.RetrieveShoppingListById(Convert.ToInt32(Request.QueryString["details"]));
                string[] ordered = sl.Date.Split('-');
                string orderedDate = string.Format("{0:0000}", ordered[2]) +
                    string.Format("{0:00}", ordered[1]) +
                    string.Format("{0:00}", ordered[0]);

                if (Convert.ToInt32(selectedReqDate) - Convert.ToInt32(orderedDate) < 7)
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
        }

        protected void datePurValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (monthPurDdl.SelectedIndex != 0 && dayPurDdl.SelectedIndex != 0 && yearPurDdl.SelectedIndex != 0)
            {
                string selectedPurDate = string.Format("{0:0000}", Convert.ToInt32(yearPurDdl.SelectedItem.Text)) +
                    string.Format("{0:00}", Convert.ToInt32(monthPurDdl.SelectedItem.Text)) +
                    string.Format("{0:00}", Convert.ToInt32(dayPurDdl.SelectedItem.Text));
                ShoppingList sl = DatabaseManager.RetrieveShoppingListById(Convert.ToInt32(Request.QueryString["details"]));
                string[] ordered = sl.Date.Split('-');
                string orderedDate = string.Format("{0:0000}", Convert.ToInt32(ordered[2])) +
                    string.Format("{0:00}", Convert.ToInt32(ordered[1])) +
                    string.Format("{0:00}", Convert.ToInt32(ordered[0]));

                if (Convert.ToInt32(selectedPurDate) - Convert.ToInt32(orderedDate) < 0)
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
        }

        protected void dateDelValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (monthDelDdl.SelectedIndex != 0 && dayDelDdl.SelectedIndex != 0 && yearDelDdl.SelectedIndex != 0)
            {
                string selectedPurDate = string.Format("{0:0000}", Convert.ToInt32(yearPurDdl.SelectedItem.Text)) +
                    string.Format("{0:00}", Convert.ToInt32(monthPurDdl.SelectedItem.Text)) +
                    string.Format("{0:00}", Convert.ToInt32(dayPurDdl.SelectedItem.Text));
                string selectedDelDate = string.Format("{0:0000}", Convert.ToInt32(yearDelDdl.SelectedItem.Text)) +
                    string.Format("{0:00}", Convert.ToInt32(monthDelDdl.SelectedItem.Text)) +
                    string.Format("{0:00}", Convert.ToInt32(dayDelDdl.SelectedItem.Text));
                ShoppingList sl = DatabaseManager.RetrieveShoppingListById(Convert.ToInt32(Request.QueryString["details"]));
                string[] ordered = sl.Date.Split('-');
                string orderedDate = string.Format("{0:0000}", Convert.ToInt32(ordered[2])) +
                    string.Format("{0:00}", Convert.ToInt32(ordered[1])) +
                    string.Format("{0:00}", Convert.ToInt32(ordered[0]));

                if ((Convert.ToInt32(selectedDelDate) - Convert.ToInt32(orderedDate) < 0)
                    || (Convert.ToInt32(selectedDelDate) - Convert.ToInt32(selectedPurDate) < 0))
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
        }

        protected void qtyValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            Regex NumbersOnly = new Regex("\\d+$");

            if (NumbersOnly.IsMatch(quantityTbx.Text))
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }

        protected void confirmationBtn_Click(object sender, EventArgs e)
        {
            int success = DatabaseManager.DeleteShoppingList(Convert.ToInt32(Request.QueryString["details"]));

            if (success == 1)
            {
                string jsPopup = "<script type='text/javascript'>" +
                        "alert('Successfully Deleted Item!');" +
                        "window.location.href = 'searchshoppinglists.aspx';" +
                        "</script>";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", jsPopup);
            }
        }
    }
}